/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package util.file.apache_commons;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Rdelacruz
 */
public class FileUtil {
    
    //http://stackoverflow.com/questions/3935791/find-and-replace-words-lines-in-a-file
    /*
    public static void replaceInFile_EnJava6(String pathname, String myPattern, String myReplacement) throws FileNotFoundException, IOException {
        String charset = StandardCharsets.UTF_8.toString();
        String content = IOUtils.toString(new FileInputStream(pathname), charset);
        content = content.replaceAll(myPattern, myReplacement);
        IOUtils.write(content, new FileOutputStream(pathname), charset);
    }*/
    
    /**
    * Will move the source File to the destination File.
    * The Method will backup the dest File, copy source to
    * dest, and then will delete the source and the backup.
    * 
    * @param source
    *            File to be moved
    * @param dest
    *            File to be overwritten (does not matter if
    *            non existent)
    * @throws IOException
    */
    //Is there an operation to move and overwrite files?
    //http://stackoverflow.com/questions/14400030/is-there-an-operation-to-move-and-overwrite-files
    public static void moveAndOverwrite(File source, File dest) throws IOException {
        // Backup the src
        File backup = util.file.FileUtil.getNonExistingTempFile(dest);
        FileUtils.copyFile(dest, backup);
        FileUtils.copyFile(source, dest);
        if (!source.delete()) {
            throw new IOException("Failed to delete " + source.getName());
        }
        if (!backup.delete()) {
            throw new IOException("Failed to delete " + backup.getName());
        }
    }


    
}
